package com.apex.crm.service;

import com.apex.crm.base.BaseController;
import com.apex.crm.base.BaseService;
import com.apex.crm.dao.UserMapper;
import com.apex.crm.dao.UserRoleMapper;
import com.apex.crm.model.UserModel;
import com.apex.crm.query.UserQuery;
import com.apex.crm.utils.AssertUtil;
import com.apex.crm.utils.Md5Util;
import com.apex.crm.utils.PhoneUtil;
import com.apex.crm.utils.UserIDBase;
import com.apex.crm.vo.Role;
import com.apex.crm.vo.User;
import com.apex.crm.vo.UserRole;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author XiaoYang
 * @version 1.0
 * @program: crm
 * @Classname UserService
 * @description TODO
 * @date 2021/4/20 18:00
 */

@Service
public class UserService extends BaseService<User,Integer> {

    @Resource
    private UserMapper userMapper;

    @Resource
    private UserRoleMapper userRoleMapper;

    @Resource
    private UserRoleService userRoleService;


    public UserModel userLogin(String userName,String userPwd){
        checkLoginParams(userName,userPwd);
        User user = userMapper.queryUserByUserName(userName);
        //System.out.println(user);
        AssertUtil.isTrue(null==user,"用户不存在或已注销");
        checkLoginPwd(userPwd,user.getUserPwd());
        return buildUserInfo(user);
    }


    @Transactional(propagation = Propagation.REQUIRED)
    public void updateUserPassword(Integer userId,String oldPassword,String newPassword,String confirmPassword){
        User user = userMapper.selectByPrimaryKey(userId);
        checkPasswordParams(user,oldPassword,newPassword,confirmPassword);
        user.setUserPwd(Md5Util.encode(newPassword));
        AssertUtil.isTrue(userMapper.updateByPrimaryKeySelective(user)<1,"用户密码更新失败!");
    }

    /**
     * 查询所有的销售人员
     * @return
     */
    public List<Map<String, Object>> queryAllSales() {
        return userMapper.queryAllSales();
    }


    //按条件查询
    public Map<String,Object> queryUserByParams(UserQuery userQuery){
        Map<String,Object> map = new HashMap<String,Object>();
        //分页
        PageHelper.startPage(userQuery.getPage(),userQuery.getLimit());
        PageInfo<User> pageInfo = new PageInfo<User>(userMapper.selectByParams(userQuery));
        map.put("code",0);
        map.put("msg","");
        map.put("count",pageInfo.getTotal());
        map.put("data",pageInfo.getList());
        //System.out.println(map);
        return map;
    }




    private UserModel buildUserInfo(User user){
        UserModel userModel = new UserModel();
        userModel.setUserIdStr(UserIDBase.encoderUserID(user.getId()));
        userModel.setUserName(user.getUserName());
        userModel.setTrueName(user.getTrueName());
        return userModel;
    }


    /*
     * @author XiaoYang
     * @description //验证登录密码
     * @date  18:21 2021/4/20
     * @param [userPwd, upwd]
     * @exception
     * @return void
     * @version 1.0
     */
    private void checkLoginPwd(String userPwd,String upwd){
        userPwd= Md5Util.encode(userPwd);
        AssertUtil.isTrue(!userPwd.equals(upwd),"用户密码不正确！");
    }

    /*
     * @author XiaoYang
     * @description  验证用户登录参数
     * @date  18:25 2021/4/20
     * @param [userName, userPwd]
     * @exception
     * @return void
     * @version 1.0
     */
    private void checkLoginParams(String userName,String userPwd){
        AssertUtil.isTrue(StringUtils.isBlank(userName),"用户姓名不能为空");
        AssertUtil.isTrue(StringUtils.isBlank(userPwd),"用户密码不能为空");
    }

    private void checkPasswordParams(User user,String oldPassword,String newPassword,String confirmPassword){
        AssertUtil.isTrue(null==user,"用户未登录或不存在！");
        AssertUtil.isTrue(StringUtils.isBlank(oldPassword),"请输入原始密码");
        AssertUtil.isTrue(!(user.getUserPwd().equals(Md5Util.encode(oldPassword))),"原始密码不正确");
        AssertUtil.isTrue(StringUtils.isBlank(newPassword),"请输入新密码！");
        AssertUtil.isTrue(oldPassword.equals(newPassword),"新密码不能与原始密码相同");
        AssertUtil.isTrue(StringUtils.isBlank(confirmPassword),"请输入确认密码！");
        AssertUtil.isTrue(!(newPassword.equals(confirmPassword)),"新密码与确认密码不一致！");
    }

    //用户参数校验
    private void checkFromParams(String userName,String email,String phone){
        AssertUtil.isTrue(StringUtils.isBlank(userName),"请输入用户名！");
        AssertUtil.isTrue(StringUtils.isBlank(email),"请输入邮箱!");
        AssertUtil.isTrue(!(PhoneUtil.isMobile(phone)),"手机号格式非法!");
    }

    public void saveUser(User user) {
        //校验传入参数
        checkFromParams(user.getUserName(),user.getEmail(),user.getPhone());
        AssertUtil.isTrue(null!=userMapper.queryUserByUserName(user.getUserName()),"用户名不能重复!");
        //逻辑存在
        user.setIsValid(1);
        //设置创建时间
        user.setCreateDate(new Date());
        user.setUpdateDate(new Date());
        //默认密码
        user.setUserPwd(Md5Util.encode("123456"));
        //添加记录
        AssertUtil.isTrue(userMapper.insert(user)<1,"用户记录添加失败");

        //添加成功后，获取添加的用户id主键
        Integer userId= userMapper.queryUserByUserName(user.getUserName()).getId();
        //获取传入的该用户角色字符串
        String roleIds=user.getRoleIds();
        //批量添加角色记录到用户角色表

        relationUserRoles(userId,roleIds);

    }

    //角色更新操作
    public  void updateUser(User user){
        //先进行参数校验
        checkFromParams(user.getUserName(),user.getEmail(),user.getPhone());
        //获取将要更新的用户信息
        User temp = userMapper.selectByPrimaryKey(user.getId());
        //判断用户是否存在
        AssertUtil.isTrue(null == temp,"待更新的用户记录不存在!");
        //查询名字是否已存在
        temp = userMapper.queryUserByUserName(user.getUserName());
        //如果名字已存在，但是id与数据库存在的id相对比不一致，则拒绝改为与该id的人同名
        AssertUtil.isTrue(null != temp && !(temp.getId().equals(user.getId())),"该用户已存在!");
        user.setUpdateDate(new Date());
        //更新信息
        AssertUtil.isTrue(userMapper.updateByPrimaryKeySelective(user) < 1,"用户记录更新失败!");
        //更新用户的角色信息
        relationUserRoles(user.getId(),user.getRoleIds());
    }



    //批量删除
    public void deleteUserByIds(Integer[] ids) {
        AssertUtil.isTrue(null == ids || ids.length == 0,"请选择待删除的用户记录!");
        //批量删除
        AssertUtil.isTrue(userMapper.deleteBatchIds(ids)!=ids.length,"用户记录删除失败!");
    }

    public User getById(Integer id) {
        return userMapper.selectByPrimaryKey(id);
    }

    //查询所有客户经理
    public List<Map<String, Object>> queryAllCustomerManager() {
        return userMapper.queryAllCustomerManager();
    }

//    //查询所有客户经理
//    public List<Map<String, Object>> queryAllCustomerManager() {
//        return userMapper.queryAllCustomerManager();
//    }


    /**
     * @author XiaoYang
     * @description //TODO  用户角色管理
     * @date  13:23 2021/5/25
     * @param [id, roleIds]
     * @exception
     * @return void
     * @version 1.0
     */
    private void relationUserRoles(Integer userId, String roleIds) {

        //查询当前用户角色表中，，当前用户有多少角色项
        Integer count = userRoleMapper.countUserRoleByUserId(userId);
        //判断角色记录是否存在
        if(count>0){
            AssertUtil.isTrue(userRoleMapper.deleteUserRoleByUserId(userId)!=count,"用户角色分配失败");
        }
        //如果角色记录存在，则删除该用户对应的角色记录
        if(StringUtils.isNotBlank(roleIds)){
            //将用户角色数据添加到集合中，批量添加
            List<UserRole> userRoleList = new ArrayList<>();
            //将用户ID字符串转换成数组
            String[] roleIdsArray = roleIds.split(",");
            //遍历数组
            for (String roleId:roleIdsArray) {
                UserRole userRole = new UserRole();
                userRole.setRoleId(Integer.parseInt(roleId));
                userRole.setUserId(userId);
                userRole.setCreateDate(new Date());
                userRole.setUpdateDate(new Date());
                //设置到集合中
                userRoleList.add(userRole);
            }
            //批量添加用户角色目录
            AssertUtil.isTrue(userRoleMapper.insertBatch(userRoleList)!=userRoleList.size(),"用户角色分配失败");
        }


    }




}



